// pages/me/wallet/wallet.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    onReachBottomLoading: false,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    userInfo:{},
    searchParams:{
      pageNum: 1,
      pageSize: 6,
      isIncome:'',
      pages:'',
      total:'',
    },
    noData: true,
    detailList:{},
    detailType:{
      'recharge':'充值',
      'payC300MtnceReport':'支付车300维保查询',
      'c300MtnceReport':'支付车300维保查询',
      'c300InsuranceReport':'支付车300碰撞查询',
      'payC300InsuranceReport':'支付车300碰撞查询',
      'refundC300MtnceReport':'车300维保查询退款',
      'refundC300InsuranceReport':'车300碰撞查询退款',
      'payCBSMtnceReport':'支付查博士维保查询',
      'cbsMtnceReport':'支付查博士维保查询',
      'payCBSInsuranceReport':'支付查博士碰撞查询',
      'cbsInsuranceReport':'支付查博士碰撞查询',
      'refundCBSMtnceReport':'查博士维保查询退款',
      'refundCBSInsuranceReport':'查博士碰撞查询退款',
      'sysGive':'系统赠送'
    },
    detailAmount:{
      balance:0,
      consumerScore:0,
      cumulativeConsumerScore:0,
      economizeAmount:0
    },
    userAgreement: true,
    modalName:null,
    priceList:[],
    hoverRechargeIndex:0,
    orderInfo:{
        orderNo:'',
        payInfo:{}
    },
    show:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  doNothing(){},
  onLoad: function (options) {
    if(options.show){
      this.setData({
        'show': options.show
      })
    }
    this.InitUserStatus();
  },
  // 检查一下登录状态。
  async InitUserStatus(){
      app.showLoading("获取用户信息");
      await app.checkToken();
      this.InitUserInfo();
      wx.hideLoading();
  },
  InitUserInfo(){
      let userInfo = app.globalData.userInfo;
      // 这里再验证一遍权限。 
      if (userInfo.roleList.indexOf('amountManage') == -1) {
          app.showNoAuthOrNoGrant('您无权操作查看此页面');
          return;
      }else{
          this.setData({
            'userInfo': userInfo
          })
          this.goQuery();
          // 获取用户的基础账户信息
          this.dealerAmountInfo();
          // 获取可用重置列表
          this.dealerAmountRechargePriceList();
      }
  },
  dealerAmountInfo(){
    app.sHttp.dealerAmountInfo().then(res=>{
      this.setData({
        'detailAmount': res.result
      })
    },err=>{
      app.error(err.msg);
    })
  },
  dealerAmountRechargePriceList(){
    app.sHttp.dealerAmountRechargePriceList().then(res=>{
      this.setData({
        'priceList': res.priceList
      });
      let self = this;
      setTimeout(() => {
        if(self.data.show == 'recharge'){
          self.setData({
            'modalName': 'bottomModal',
            'show':''
          })
        }
      }, 200);
    },err=>{
      app.error(err.msg);
    })
  },
  
  goQuery(){
    this.setData({
      'searchParams.pageNum':1,
      'searchParams.total':'',
      'searchParams.pages':'',
      'detailList': {}
    });
    this.dealerAmountDetailList(this.data.searchParams);
  },
  dealerAmountDetailList(searchParams){
    // 整理完成进行搜索操作。
    this.setData({
        'onReachBottomLoading': true
    })
    app.sHttp.dealerAmountDetailList(searchParams).then(res=>{
        let detailList = this.data.detailList;
        detailList[searchParams.pageNum] = res.result.detailList;
        if (0 == res.result.total) {
          this.setData({
            'noData': true,
            'onReachBottomLoading': false
          })
        }else{
          this.setData({
            'noData': false,
            'detailList': detailList,
            'searchParams.total':res.result.total,
            'searchParams.pages': res.result.pages,
            'onReachBottomLoading': false
          });
        }
      },err=>{
        app.error(err.msg);
        this.setData({
          'onReachBottomLoading': false
        })
    })
  },
  onReachBottom(){
      if (this.data.searchParams.pageNum == this.data.searchParams.pages) {
          //app.alert('没有更多了哦~');
      }else{
          let self = this;
          this.setData({
              'searchParams.pageNum': self.data.searchParams.pageNum+1
          });
          this.dealerAmountDetailList(this.data.searchParams);
      }
  },
  switchType(e){
    let type = e.currentTarget.dataset.type;
    let _this = this;
    this.setData({
        'searchParams.isIncome': type
    },(res)=>{
      _this.goQuery();
    });
  },
  copyOrderNo(e){
    let order = e.currentTarget.dataset.order;
    wx.setClipboardData({
      data: order,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '已为您复制到粘贴板',
              icon:'none'
            })
          }
        })
      }
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      orderInfo:{
          orderNo:'',
          payInfo:{}
      }
    });
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    });
  },
  useUserAgreement(){
    this.setData({
      userAgreement: !this.data.userAgreement
    })
  },
  choosePay(e){
    this.setData({
      'hoverRechargeIndex': e.currentTarget.dataset.idx
    })
  },
  preparePay(){
    if(!this.data.userAgreement){
      app.alert('请勾选用户协议');
      return;
    }
    try {
      let priceItem = this.data.priceList[this.data.hoverRechargeIndex];
      if(priceItem){
        app.sHttp.dealerAmountOrderCreate(priceItem.rechargeId).then(res =>{
          let self = this;
          this.setData({
              'orderInfo.orderNo': res.result.orderNo,
              'orderInfo.payInfo': res.result.payInfo
          }, () => {
              self.tuneUpPay();
          });
      },err=>{
        app.error(err.msg);
      })
      }else{
        app.alert('充值信息不存在,请关闭重试。');
      }
      
    } catch (error) {
      app.alert('充值信息不存在,请关闭重试。');
    }
  },    
  tuneUpPay(){
    // 从Data里面拿参数
    let orderInfo = this.data.orderInfo;
    if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
        app.alert('支付参数不完整');
        return;
    };
    // 吊起支付。
    let self = this;
    wx.requestPayment({
        timeStamp: orderInfo.payInfo.timeStamp,
        nonceStr: orderInfo.payInfo.nonceStr,
        package: orderInfo.payInfo.package,
        signType: orderInfo.payInfo.signType,
        paySign: orderInfo.payInfo.paySign,
        success (res) {
            // 查询订单完成信息。
            let _this = self;
            app.showLoading('查询订单状态');
            setTimeout(() => {
                wx.hideLoading();
                _this.dealerAmountOrderPayResult();
            }, 5000);
        },
        fail (res) {
            app.alert('您已取消支付');
        }
      })
  },
  dealerAmountOrderPayResult(){
      let orderInfo = this.data.orderInfo;
      if ('' == orderInfo.orderNo) {
          app.alert('支付参数不完整');
          return;
      };
      app.sHttp.dealerAmountOrderPayResult(orderInfo.orderNo).then(res =>{
          let orderStatus = res.orderStatus;
          if (0 == orderStatus) {
              this.wxShowModal('查询结果','请等待几分钟后重新进入查看是否充值，如长时间未显示成功状态，请联系客服处理');
              return;
          }else if (1 == orderStatus) {
              this.wxShowModal('充值成功','您已支付成功');
              return;
          }else{
            this.wxShowModal('查询结果','请等待几分钟后刷新查看，如长时间未显示成功状态，请联系客服处理');
          }
      },err=>{
        app.error(err.msg);
      })
  },
  wxShowModal(title,content){
      let self = this;
      wx.showModal({
          title: title,
          content: content,
          confirmText: '我知道了',
          showCancel: false,
          success(res) {
              self.hideModal();
              self.InitUserInfo();
          }
        })
  },

  jumpToUserAgreement(){
    this.hideModal();
    wx.navigateTo({
      url: '/pages/publicPage/userAgreement/userAgreement',
    })
  },
  openCustomerServiceChat(){
    this.hideModal();
    app.openCustomerServiceChat();
  },
})